package com.mifengs.mall.util;

import android.app.Activity;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.mifengs.commonbase.util.LogUtil;
import com.mifengs.mall.Constant;
import com.mifengs.mall.entity.PayResult;
import com.mifengs.mall.entity.PayWay;
import com.mifengs.mall.entity.RechargeWay;
import com.mifengs.mall.entity.ResponseInfo;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by lihaoqi on 2017/5/15.
 */

public class PayWayUtils {

    private Activity mActivity;


    public static HashMap<Integer,String> getPayWay(){
        HashMap<Integer,String> mPaywayMap = new HashMap<>();
        mPaywayMap = new HashMap<>();
        mPaywayMap.put(PayWay.PAY_WALLET.code, "钱包");
        mPaywayMap.put(PayWay.PAT_ZFB_QUICK.code, "支付宝闪付");
        mPaywayMap.put(PayWay.PAY_WEIXIN_QUCIK.code, "微信闪付");
        mPaywayMap.put(PayWay.PAY_YIN_LIAN_QUICK.code, "银联闪付");
        mPaywayMap.put(PayWay.PAY_ZFB.code, "支付宝支付");  //支付宝一般
        mPaywayMap.put(PayWay.PAY_WEIXIN.code, "微信支付");  //微信一般
        mPaywayMap.put(PayWay.PAY_YINLIAN.code, "银联支付");  //银联一般
        return mPaywayMap;
    }

    public static HashMap<Integer,String> getRechargeWay(){
        HashMap<Integer,String> mPaywayMap = new HashMap<>();
        mPaywayMap = new HashMap<>();
        mPaywayMap.put(RechargeWay.RECHARGE_ZFB_QUICK.code, "支付宝闪付");
        mPaywayMap.put(RechargeWay.RECHARGE_WEIXIN_QUCIK.code, "微信闪付");
        mPaywayMap.put(RechargeWay.RECHARGE_YIN_LIAN_QUICK.code, "银联闪付");
        mPaywayMap.put(RechargeWay.RECHARGE_ZFB.code, "支付宝支付");  //支付宝一般
        mPaywayMap.put(RechargeWay.RECHARGE_WEIXIN.code, "微信支付");  //微信一般
        mPaywayMap.put(RechargeWay.RECHARGE_YINLIAN.code, "银联支付");  //银联一般
        return mPaywayMap;
    }

    public PayWayUtils(Activity activity) {
        this.mActivity = activity;
    }


    private Func1<ResponseInfo<String>, Observable<String>> payFunc1 =
            new Func1<ResponseInfo<String>, Observable<String>>() {
                @Override
                public Observable<String> call(ResponseInfo<String> stringResponseInfo) {
                    return creatMyObservable(stringResponseInfo);
                }
            };


    public Func1<ResponseInfo<String>, Observable<String>> getPayFunc1() {
        return payFunc1;
    }


    private Observable<String> creatMyObservable(final ResponseInfo<String> stringResponseInfo){
        return  Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                if(stringResponseInfo.getStatus()== Constant.OK_CODE){
                    subscriber.onNext(stringResponseInfo.getResult());
                    subscriber.onCompleted();
                }else if(stringResponseInfo.getStatus() == -1){
                    subscriber.onError(new Exception("请重新登录"));
                }else{
                    subscriber.onError(new Exception(stringResponseInfo.getMsg()));
                }
            }
        });
    }

    //支付宝支付
    //_______________________________________________________________________________________________________________________



    private Func1<String, Observable<String>> rechargeZfbFunc1 =
            new Func1<String, Observable<String>>() {
                @Override
                public Observable<String> call(String s) {
                    //EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX); //沙箱模式
                    PayTask ailPay = new PayTask(mActivity);
                    Map<String,String> result = ailPay.payV2(s,true);
                    LogUtil.i("aliPay:",result.toString());
                    return creatZhifuBaoObservable(result);
                }
            };

    public Func1<String, Observable<String>> getRechargeZfbFunc1() {
        return rechargeZfbFunc1;
    }

    private Observable<String> creatZhifuBaoObservable(final Map<String,String> result){

        return  Observable.create(new Observable.OnSubscribe<String>() {

            @Override
            public void call(Subscriber<? super String> subscriber) {
                PayResult payResult = new PayResult(result);
                /**
                 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                 */
                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                String memo = payResult.getMemo();
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    subscriber.onNext(resultInfo);
                    subscriber.onCompleted();
                }else {
                    subscriber.onError(new Exception(memo));
                }
            }
        });
    }

    //微信支付
    //____________________________________________________________________________________________________

    private Func1<String, Observable<String>> rechargeWeiXinFunc1 =
            new Func1<String, Observable<String>>() {
                @Override
                public Observable<String> call(String s) {
                    return creatWeiXinObservable(s);
                }
            };

    public Func1<String, Observable<String>> getRechargeWeiXinFunc1() {
        return rechargeWeiXinFunc1;
    }

    private Observable<String> creatWeiXinObservable(final String s) {
        return  Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                    try {
                        IWXAPI api = WXAPIFactory.createWXAPI(mActivity,null);
                        api.registerApp(Constant.WEIXIN_APPID);
                        JSONObject json = new JSONObject(s);
                        //if(null != json&&(json.getString("resultCode").equals("SUCCESS"))){
                            PayReq req = new PayReq();
                            req.appId			= json.getString("appid");
                            req.partnerId		= json.getString("partnerid");
                            req.prepayId		= json.getString("prepayid");
                            req.nonceStr		= json.getString("noncestr");
                            req.timeStamp		= json.getString("timestamp");
                            req.packageValue	= json.getString("package");
                            req.sign			= json.getString("sign");
                            // 判断调起成功或失败
                            if(api.sendReq(req)){
//                                String outTradeNo = json.getString("outTradeNo");
                                subscriber.onNext("weixin start success");
                                subscriber.onCompleted();
                            }else{
                                subscriber.onError(new Exception("weixin start fail"));
                            }
//                        }else{
//                            subscriber.onError(new Exception(json.getString("errCodeDesc")));
//                        }
                    } catch (JSONException e) {
                        subscriber.onError(e);
                    }
            }
        });
    }

    public void wxPayVerify(HashMap<String, String> hashMap,Observer<ResponseInfo<String>> observer) {
//        NetWork.getWeiXinVerifyApi().verify(hashMap)
//                .subscribeOn(Schedulers.io())
//                .compose(((RxAppCompatActivity)mWeakReferenceActivity.get()).<ResponseInfo<String>>bindToLifecycle())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(observer);
    }




}
